<template>
  <div class="play-bar" :class="{show:!toggle}">
    <audio
        ref="player"
        :src="audio.url"
        controls="controls"
        preload="true"
        @canplay="startPlay"
        @ended="ended"
        @timeupdate="timeUpdate"
        style="display:none"
    >
    </audio>
    <div @click="toggle=!toggle" class="item-up" :class="{turn: toggle}">
      <svg class="icon">
        <use xlink:href="#icon-jiantou-shang-cuxiantiao"></use>
      </svg>
    </div>
    <div class="kongjian">
      <!--    上一首-->
      <div class="item" @click="previousSong">
        <svg class="icon">
          <use xlink:href="#icon-ziyuanldpi"></use>
        </svg>
      </div>
      <!--    播放-->
      <div class="item" @click="togglePlay">
        <svg class="icon">
          <use v-if="audio.isPlay==false" xlink:href="#icon-bofang"></use>
          <use v-if="audio.isPlay==true" xlink:href="#icon-zanting"></use>
        </svg>
      </div>
      <!--    下一首-->
      <div class="item" @click="nextSong">
        <svg class="icon">
          <use xlink:href="#icon-ziyuanldpi1"></use>
        </svg>
      </div>
      <!--    图片-->
      <div class="item-img" @click="showSongInfo(audio.lyric)">
        <img :src="audio.picUrl">
      </div>
      <!--    播放进度-->
      <div class="playing-speed">
        <div class="current-time">
          {{audio.curTime}}
        </div>
        <div class="progress-box">
          <div class="item-song-title">
            <div>{{this.audio.title}}</div>
            <div>{{this.audio.artist}}</div>
          </div>
          <div class="progress" ref="progress" @mousemove="mousemove">
            <!--          进度条-->
            <div ref="bg" class="bg" @click="updateMove">
              <div ref="curProgress" class="cur-progress" :style="{width:audio.curLength+'%'}">
                <!--拖动的点-->
                <div class="idot" ref="idot" :style="{left:audio.curLength+'%'}" @mousedown="mousedown" @mouseup="mouseup"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="left-time">
          {{audio.duration}}
        </div>
        <!--      音量-->
        <div class="item item-volume">
          <svg v-if="audio.volume == 0" class="icon">
            <use xlink:href="#icon-yinliangjingyinheix"></use>
          </svg>
          <svg v-else class="icon">
            <use xlink:href="#icon-yinliang1"></use>
          </svg>
          <el-slider class="volume" v-model="audio.volume" :vertical="true"></el-slider>
        </div>
        <!--      喜欢-->
        <div class="item" @click="addOrDeleteCollect">
          <svg  :class="{active:isActive}" class="icon">
            <use xlink:href="#icon-xihuan-shi"></use>
          </svg>
        </div>
        <!--      下载-->
        <div class="item item-volume" @click="download(audio.url)">
          <svg class="icon">
            <use xlink:href="#icon-xiazai"></use>
          </svg>
        </div>
        <!--      当前播放的列表-->
        <div class="item" @click="showListOfSong">
          <svg class="icon">
            <use xlink:href="#icon-liebiao"></use>
          </svg>
        </div>
      </div>
    </div>
    <transition name="slide-fade">
      <div class="the-aside" v-if="isShow">
        <h2 class="title">播放列表</h2>
        <ul class="menus">
          <li v-for="(item,index) in listOfSong" :key="index" :class="{'is-play': audio.id==item.id}" @click="playSong(item,index)">
            {{item.name}}
          </li>
        </ul>
      </div>
    </transition>
  </div>
</template>

<script>
import {mapState} from 'vuex'
export default {
  name: "SongAudio",
  data(){
    return{
      audio:{
        id:0,
        url:'',
        isPlay:false,
        duration:0 ,//音乐时常
        curTime:0 , //播放位置
        curLength:0,   //进度条位置
        changeTime:0,  //指定播放时刻
        title:'' ,      //歌名
        artist:'' ,      //歌手名
        picUrl: ''  ,   //歌曲图片
        autoNext:true ,  //自动触发播放下一首
        lyric:[]  , //歌词,
        tempList:{},  //单个歌单信息
        listIndex:0, //当前歌曲在歌单的位置
        volume:50  ,  //默认音量
        progressLength:0,   //进度条总长度
        mouseStartX:0,      //拖拽开始位置
        tag:false,          //拖拽开始结束的标志，当开始拖拽，变为true
      },
      isShow:false,
      listOfSong:[],
      toggle:true, //显示/隐藏播放器
      isActive:false,  //是否收藏
      collectId:''     //收藏主键
    }
  },
  watch:{
    //深度监听
    audio:{
      handler: function () {
        this.$refs.player.volume= this.audio.volume/100
        this.audio.curLength=(this.$refs.player.currentTime/this.$refs.player.duration)*100
        this.audio.changeTime=this.$refs.player.currentTime
        this.$bus.$emit('curTime',this.$refs.player.currentTime)
      },
      //开启深度监听
      deep: true
    }
  },
  methods:{
    startPlay(){
      let player=this.$refs.player
      this.audio.duration=this.formatSeconds(player.duration)
      this.audio.isPlay=true
      player.play()
    },
    ended(){
      this.audio.isPlay=false
      this.nextSong()
    },
    //开始，暂停
    togglePlay(){
      let player=this.$refs.player
      if (this.audio.isPlay){
        this.audio.isPlay=false
        player.pause()
      }else {
        this.audio.isPlay=true
        player.play()
      }
    },
    //记录音乐播放位置
    timeUpdate(){
     this.audio.curTime=this.formatSeconds(this.$refs.player.currentTime)
    },
    //解析时间
    formatSeconds(value){
      let myTime=parseInt(value)
      let hour =parseInt(myTime/3600)//时
      let minute = parseInt((myTime/60)%60)//分
      let second=parseInt(myTime%60)//秒
      let result=''
      if(hour>0){
        if (hour<10){
          result= '0'+hour+":"
        }else {
          result=hour+':'
        }
      }
      if (minute>0){
        if (minute<10){
          result+='0'+minute+':'
        }else {
          result+=minute+':'
        }
      }else{
        result+='00:'
      }
      if (second>0){
        if (second<10){
          result+='0'+second
        }else {
          result+=second
        }
      }else {
        result+='00'
      }
      return result
    },
    //拖拽开始
    mousedown(e){
      this.audio.mouseStartX = e.clientX;
      this.audio.tag = true;
    },
    //拖拽结束
    mouseup(){
      this.audio.tag = false;
    },
    //拖拽中
    mousemove(e){
      if(!this.audio.duration){
        return false;
      }
      if(this.audio.tag){
        let movementX = e.clientX - this.audio.mouseStartX;       //点点移动的距离
        let curLength = this.$refs.curProgress.getBoundingClientRect().width;
        let newPercent = ((movementX+curLength)/this.audio.progressLength)*100;
        if(newPercent>100){
          newPercent = 100;
        }
        this.audio.mouseStartX = e.clientX;
        this.changeTime(newPercent);
      }
    },
    //更改歌曲进度
    changeTime(percent){
        let newCurTime=(percent*0.01)*this.$refs.player.duration
        this.$refs.player.currentTime=newCurTime
    },
    //改变进度条位置
    updateMove(e){
      if(!this.audio.tag){
        //进度条的左侧坐标
        let curLength = this.$refs.bg.offsetLeft;
        let newPercent = ((e.clientX - curLength) / this.audio.progressLength) * 100;
        if(newPercent>100){
          newPercent = 100;
        }else if(newPercent<0){
          newPercent = 0;
        }
        this.audio.curLength = newPercent;
        this.changeTime(newPercent);
      }
    },
    //展示歌单列表
    showListOfSong(){
      this.isShow=!this.isShow
    },
    //播放列表歌曲
    playSong(item,index){
      this.audio.listIndex=index
      this.audio.id=item.id
      this.audio.url=item.url
      this.audio.lyric=item.lyric
      this.audio.title=item.name.split('-')[1]
      this.audio.artist=item.name.split('-')[0]
      this.audio.picUrl=item.pic
    },
    //上一首
    previousSong(){
     if (this.listOfSong.length>1){
       if (this.audio.listIndex==0){
         this.audio.listIndex=this.listOfSong.length-1
       }else{
         this.audio.listIndex-=1
       }
       this.playSong(this.listOfSong[this.audio.listIndex],this.audio.listIndex)
     }
    },
    //下一首
    nextSong(){
      if (this.listOfSong.length>1){
        if (this.audio.listIndex<this.listOfSong.length-1){
          this.audio.listIndex+=1
        }else{
          this.audio.listIndex=0
        }
        this.playSong(this.listOfSong[this.audio.listIndex],this.audio.listIndex)
      }
    },
    //歌曲详情
    showSongInfo(lyric){
      this.$store.commit('LYRIC',lyric)
      this.$router.push('/songInfo')
    },
    //下载歌曲
    download(url) {
      if (url==""){
        this.$notify.warning('亲！还未点播歌曲')
      }else {
        this.$notify.warning('该功能还未开发出来')
      }
    },
    //添加收藏
   async addOrDeleteCollect(){
      if (localStorage.getItem('Token')){
        if (this.isActive){
          //已收藏
          await this.findCollectId()
          let result=await this.$API.reqDeleteCollect(this.collectId)
          if (result.code==10000){
            this.isActive=false
            this.$notify.success('取消收藏成功')
          }else {
            this.$notify.error('系统异常')
           await Promise.reject(new Error('fail'))
          }
        }else {
          //没有收藏
          let params=new URLSearchParams()
          params.append('userId',this.userId)
          params.append('type',0)
          params.append('songId',this.audio.id)
          let result=await this.$API.reqAddCollect(params)
          if (result.code==10000){
            this.isActive=true
            this.$notify.success('收藏成功!')
          }else if (result.code==20008){
            this.$notify.warning('已收藏该歌曲!')
          }
        }
      }else {
        this.$notify.error('请先登录！')
      }
    },
    //检查用户是否收藏
   async isCollect(){
      let result=await this.$API.reqCheckInSong(this.userId,this.audio.id)
      if (result.code==20008){
        this.isActive=true
      }else if (result.code==10000){
        this.isActive=false
      }else {
       await Promise.reject(new Error('fail'))
      }
    },
    //查询该用户下的该歌曲的主键
    async findCollectId(){
    let result=await this.$API.reqShowCollectId(this.userId,this.audio.id)
      if (result.code==10000){
        this.collectId=result.data.id
      }else {
       await Promise.reject(new Error('fail'))
      }
    }
  },
  mounted() {
    this.$bus.$on('searchPlaySong',(item)=>{
      if (this.audio.id!=item.id){
        this.audio.id=item.id
        this.audio.url=item.url
        this.audio.lyric=item.lyric
        this.audio.title=item.name.split('-')[1]
        this.audio.artist=item.name.split('-')[0]
        this.audio.picUrl=item.pic
        this.isCollect()
      }
    })
    this.$bus.$on('songList',(item)=>{
      if (this.audio.id!=item.id) {
        this.audio.id = item.id
        this.audio.url = item.url
        this.audio.lyric = item.lyric
        this.audio.title = item.name.split('-')[1]
        this.audio.artist = item.name.split('-')[0]
        this.audio.picUrl = item.pic
        this.listOfSong.push(item)
        this.isCollect()
      }
    })
    this.$bus.$on('listOfSong',(listOfSong)=>{
        this.listOfSong=listOfSong
    })
    this.audio.progressLength=this.$refs.progress.getBoundingClientRect().width
    document.querySelector('.item-volume').addEventListener('click',function(e){
      document.querySelector('.volume').classList.add('show-volume');
      e.stopPropagation()
    },false)
    document.querySelector('.volume').addEventListener('click',function(e){
      e.stopPropagation()
    },false)
    document.addEventListener('click',function(){
      document.querySelector('.volume').classList.remove('show-volume');
    },false)
  },
  computed:{
    ...mapState({
      userId:state => state.home.userId
    })
  }
}
</script>

<style scoped lang="scss">
@import "../assets/css/play-bar.scss";
@import '../assets/css/the-aside.scss';
</style>
